/**
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import request from '@/soar/utils/request';
import { signin } from '@/soar/utils/token';
import md5 from '@/soar/js_sdk/spark-md5.js';
import sm2 from '@/soar/js_sdk/sm2.js';
import { sm2DynamicPKI } from './common';

const baseUrl = '/system/login';

/**
 * 使用密码登录
 * @param parameter {
 *     username： 用户名
 *     password：密码（MD5值）
 *     captcha：验证码
 * }
 * @returns {*}
 */
export function account(parameter: any): Promise<any> {
    parameter = { ...parameter };
    return new Promise((resolve, reject) => {
        sm2DynamicPKI('login')
            .then((res) => {
                res = res.data
                parameter.account = '04' + sm2.doEncrypt(parameter.account.trim(), res);
                parameter.password = '04' + sm2.doEncrypt(md5.hash(parameter.password.trim()), res);
                parameter.captcha = parameter.captcha?.trim();
                parameter.encrypted = true;
                request
                    .post(`${baseUrl}/account`, {
                        title: '登录',
                        successMsg: '欢迎回来',
                        data: parameter,
                    })
                    .then((res) => {
                        signin(res.data);
                        resolve(res);
                    })
                    .catch(reject);
            })
            .catch(reject);
    });
}
